<template>
  <div class="pure-container">
    <!-- 查询条件处理 盒子-->
    <div v-if="isShowSearchForm" ref="formContainerRef" class="form-container">
      <a-form :model="queryParam" layout="inline" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" @submit="onSubmit">
        <a-form-item label="立项名称：" name="projectName">
          <a-input v-model:value="queryParam.projectName" placeholder="请输入立项名称" />
        </a-form-item>

        <a-form-item label="立项编码：" name="projectCode">
          <a-input v-model:value="queryParam.projectCode" placeholder="请输入立项编码" />
        </a-form-item>

        <a-form-item label="项目类别：" name="projectType">
          <j-dict-select-tag v-model:value="queryParam.projectType" dictCode="project" placeholder="请选择项目类别" allow-clear />
        </a-form-item>

        <a-form-item v-if="toggleSearchStatus" label="集团归口部门：" name="hasSubBudget">
          <a-input v-model:value="queryParam.hasSubBudget" placeholder="请选择项目部门">
            <template #addonAfter>
              <div @click="openModalClick('hasSubBudget')">
                <MenuUnfoldOutlined />
              </div>
            </template>
          </a-input>
          <DepartmentSelect
            :ref="(el) => el && (modalRefs['hasSubBudget'] = el)"
            @change="(value, options) => onChangeOfModal(value, options, 'hasSubBudget', 'department_name')"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 2, span: 24 }">
          <a-space>
            <a-button type="primary" html-type="submit">查询</a-button>
            <a-button @click="resetForm">重置</a-button>
            <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
              {{ toggleSearchStatus ? '收起' : '展开' }}
              <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
            </a>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
    <!-- 表格盒子 -->
    <div ref="tableContainerRef" class="table-container">
      <div v-if="loading" class="loading-container">
        <a-spin size="large" />
      </div>
      <div class="operation-box">
        <div class="flex items-center">
          <div class="cyj-basic-table-header__tableTitle">
            <a-button
              v-auth="'purProCopy:project_proposal_preparation_copy:add'"
              type="primary"
              preIcon="ant-design:plus-outlined"
              @click="handleCreate"
              >新增</a-button
            >
            <a-button v-auth="'purProCopy:project_proposal_preparation_copy:exportXls'" preIcon="ant-design:export-outlined" @click="onExportXls"
              >导出</a-button
            >
            <j-upload-button
              v-auth="'purProCopy:project_proposal_preparation_copy:importExcel'"
              preIcon="ant-design:import-outlined"
              @click="onImportXls"
              >导入</j-upload-button
            >
            <super-query :config="superQuerySchema" @search="handleSuperQuery" />

            <a-dropdown v-if="hasSelected">
              <template #overlay>
                <a-menu>
                  <a-menu-item :disabled="batchDelDisabled" key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined" />
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button
                >批量操作
                <Icon icon="ant-design:down-outlined" />
              </a-button>
            </a-dropdown>
          </div>

          <div class="cyj-basic-table-header__toolbar"> </div>
        </div>
        <div class="info-box">
          <a-alert type="info" show-icon class="alert">
            <template #message>
              <template v-if="hasSelected">
                <span>
                  <span>已选中 {{ selectedRowKeys.length }} 条记录</span>
                </span>
                <a-divider type="vertical" />
                <a @click="setSelectedRowKeys([])">清空</a>
              </template>
              <template v-else>
                <span>未选中任何数据</span>
              </template>
            </template>
          </a-alert>
        </div>
      </div>

      <div class="table-page-container">
        <div class="vex-table-container">
          <vxe-table
            header-row-class-name="vex-table-header"
            header-cell-class-name="vex-table-header-cell"
            row-class-name="vex-table-row"
            cell-class-name="vex-table-cell"
            :row-config="{ isHover: true }"
            @checkbox-all="selectAllChangeEvent"
            @checkbox-change="selectChangeEvent"
            header-align="center"
            ref="tableRef"
            id="id"
            size="mini"
            align="center"
            border="inner"
            max-height="100%"
            :loading="loading"
            :data="data"
          >
            <vxe-column type="checkbox" width="60" />
            <!-- <vxe-column type="seq" title="序号" width="70" /> -->
            <vxe-column
              v-for="item in columns"
              :key="item.dataIndex"
              :field="item.dataIndex"
              :title="item.title"
              :formatter="item.formatter"
              :align="item.align ?? 'center'"
            />
            <vxe-column field="operation" title="操作" width="150">
              <template #default="{ row }">
                <PopConfirmButton
                  :disabled="editBtnDisabled(row)"
                  :enable="true"
                  type="link"
                  size="small"
                  :open="false"
                  color="success"
                  @click="handleEdit(row)"
                  label="编辑"
                >
                  编辑
                </PopConfirmButton>
                <!-- <Divider type="vertical" class="action-divider" /> -->
                <a-dropdown>
                  <a-button type="link" size="small"> 更多 <Icon icon="mdi-light:chevron-down" /> </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item key="1">
                        <PopConfirmButton
                          :enable="false"
                          :open="false"
                          type="link"
                          size="small"
                          color="info"
                          @click="handlePreview(row)"
                          label="详情"
                        >
                          详情
                        </PopConfirmButton>
                      </a-menu-item>
                      <a-menu-item key="2">
                        <PopConfirmButton
                          :disabled="isDeleteBtnDisabled(row)"
                          overlayClassName="cyj-basic-table-action-popconfirm"
                          type="link"
                          size="small"
                          color="error"
                          title="确定删除吗?"
                          @confirm="deleteConfirm(row)"
                          label="删除"
                        >
                          删除
                        </PopConfirmButton>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </vxe-column>
            <template #empty>
              <div class="empty-box">
                <img :src="noDataPng" alt="" />
                <div>暂无数据</div>
              </div>
            </template>
            <!-- <template #loading>
              <div class="loading-container">
                <a-spin size="large"/>
              </div>
            </template> -->
          </vxe-table>
        </div>
        <Pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-total="pagination.showTotal"
          showSizeChanger
          :page-size-options="pagination.pageSizeOptions"
          showQuickJumper
          size="small"
          @change="handleTableChange"
        />
      </div>
    </div>

    <BasicModal
      v-bind="$attrs"
      wrapClassName="approval-form-modal"
      :destroyOnClose="true"
      :footer="null"
      :title="approvalModal.title"
      :width="896"
      :canFullscreen="true"
      :defaultFullscreen="true"
      @register="registerApprovalModal"
    >
      <ProjectProposalPreparationApproval
        :isInModal="true"
        :formBpm="false"
        :formDisabled="approvalModal.disabled"
        :recordId="approvalModal.recordId"
        :processInstanceId="approvalModal.processInstanceId"
        :processStatus="approvalModal.processStatus"
        :operate="approvalModal.operate"
        :isApprovalNew="approvalModal.isApprovalNew"
        @success="handleSuccess"
      ></ProjectProposalPreparationApproval>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import noDataPng from '/@/assets/images/table_nodata.png';
  import { ref, reactive, computed, onMounted, nextTick } from 'vue';
  import { Divider, Pagination } from 'ant-design-vue';
  import { PopConfirmButton } from '/@/components/Button';
  import { useModal } from '/@/components/Modal';
  import { useMethods } from '/@/hooks/system/useMethods';
  import { VxeTableInstance, VxeTableEvents } from 'vxe-table';
  import { getExportUrl, getImportUrl, list, deleteOne, batchDelete } from './ProjectProposalPreparation.api';
  import { filterObj } from '/@/utils/common/compUtils';
  import ProjectProposalPreparationApproval from './ProjectProposalPreparationApproval.vue';
  import { BasicModal } from '/@/components/Modal';
  import { superQuerySchema, columns } from './ProjectProposalPreparation.data';
  import DepartmentSelect from '/@/components/Form/src/cyj/components/DepartmentSelectNative.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { useWindowSizeFn } from '/@/hooks/event/useWindowSizeFn';
  import { onMountedOrActivated } from '/@/hooks/core/onMountedOrActivated';
  import { MenuUnfoldOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { hasPermission } = usePermission();
  const userStore = useUserStore();
  const modalRefs = ref({});
  /**部门选择 */
  const openModalClick = (field: string) => {
    modalRefs.value[field].openModalClick();
  };
  const onChangeOfModal = (value: any, options: any, paramsField: string, valueField: string) => {
    queryParam[paramsField] = options.map((item) => item[valueField]);
  };

  const deletePermission = computed(() => hasPermission('purProCopy:project_proposal_preparation_copy:delete'));
  const editPermission = computed(() => hasPermission('purProCopy:project_proposal_preparation_copy:edit'));

  const approvalModal = ref<any>({
    title: '新增',
    operate: '',
    recordId: '',
    processInstanceId: '',
    processStatus: '',
    disabled: false,
    isApprovalNew: 0,
  });

  const handleSuperQuery = (params) => {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    onSubmit();
  };
  /**高级查询 */

  /**展开按钮 */
  const toggleSearchStatus = ref<boolean>(false);
  /**展开按钮 */

  //model
  const [registerApprovalModal, { openModal: openApprovalModal, closeModal: closeApprovalModal }] = useModal();

  const queryParam = reactive<any>({});

  const resetForm = () => {
    initSetQueryParam();
    pagination.current = 1;
    pagination.pageSize = 10;
    getList();
  };

  const initSetQueryParam = () => {
    Object.keys(superQuerySchema).forEach((field) => {
      const info = superQuerySchema[field];
      const valueType = info.type;
      if (valueType) {
        queryParam[field] = null;
      }
    });
    Object.keys(queryParam).forEach((field) => {
      queryParam[field] = null;
    });
  };
  initSetQueryParam();

  const onSubmit = () => {
    getList();
  };

  const handleEdit = (record) => {
    approvalModal.value.title = '编辑';
    approvalModal.value.operate = 'edit';
    approvalModal.value.disabled = false;
    approvalModal.value.recordId = record.id;
    approvalModal.value.processInstanceId = record.processInstanceId;
    approvalModal.value.processStatus = record.processStatus;
    approvalModal.value.isApprovalNew = new Date().getTime();

    openApprovalModal(true, {
      isUpdate: true,
      record,
    });
  };

  const handlePreview = (record) => {
    approvalModal.value.title = '查看';
    approvalModal.value.operate = 'view';
    approvalModal.value.disabled = true;
    approvalModal.value.recordId = record.id;
    approvalModal.value.processInstanceId = record.processInstanceId;
    approvalModal.value.processStatus = record.processStatus;
    approvalModal.value.isApprovalNew = new Date().getTime();

    openApprovalModal(true, {
      isUpdate: true,
      readonly: true,
      record,
    });
  };

  const editBtnDisabled = (record: any) => {
    let disabled = record.processStatus !== 'DRAFT';
    if (!disabled) {
      const userId = userStore.getUserInfo.id;
      if (userId !== record.createBy) {
        disabled = true;
      }
    }
    if(!disabled){
      disabled = !editPermission.value
    }
    return disabled;
  };

  const isDeleteBtnDisabled = (record: any) => {
    let disabled = record.processStatus !== 'DRAFT'
    if(!disabled){
      disabled = !deletePermission.value
    }
    return disabled
  }

  // 删除确认
  const deleteConfirm = async (record) => {
    await deleteOne(
      {
        id: record.id,
      },
      handleSuccess
    );
  };

  const batchHandleDelete = async () => {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  };

  const handleSuccess = () => {
    closeApprovalModal();
    (selectedRowKeys.value = []) && getList();
  };
  /**表单查询 */

  /**操作栏按钮逻辑 */
  const handleCreate = () => {
    approvalModal.value.title = '新增';
    approvalModal.value.operate = 'create';
    approvalModal.value.disabled = false;
    approvalModal.value.recordId = '';
    approvalModal.value.processInstanceId = '';
    approvalModal.value.processStatus = '';
    approvalModal.value.taskId = '';
    approvalModal.value.isApprovalNew = new Date().getTime();

    openApprovalModal(true, {
      isUpdate: false,
    });
  };

  const { handleExportXls, handleImportXls } = useMethods();
  const onExportXls = () => {
    handleExportXls(
      '项目立项编制主表',
      getExportUrl,
      filterObj({
        ...queryParam,
        selections: selectedRowKeys.value.join(','),
      })
    );
  };

  const onImportXls = (file) => {
    handleImportXls(file, getImportUrl, handleSuccess);
  };
  /**操作栏按钮逻辑 */

  interface listItem {
    id: string;
    [key: string]: string;
  }

  const data = ref<listItem[]>([]);
  /**列表配置 */

  /**列表数据 */
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 60,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100'],
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条数据`,
    size: 'small',
  });

  const loading = ref<boolean>(false);

  const getList = async () => {
    loading.value = true;
    try {
      const res = await list({
        column: 'createTime',
        order: 'desc',
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        ...queryParam,
      });
      data.value = res.records as listItem[];
      pagination.total = res.total;
    } finally {
      loading.value = false;
    }
  };

  onMounted(async () => {
    getList();
  });

  // 表格变化处理（分页、排序）
  const handleTableChange = (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getList();
  };
  /**列表数据 */

  /**列表选中相关内容 */
  type Key = string | number;
  const selectedRowKeys = ref<Key[]>([]);
  const selectedRowRecords = ref<Key[]>([]);
  const tableRef = ref<VxeTableInstance<listItem>>();

  // 批量删除禁用
  const batchDelDisabled = computed(() => {
    let disabled = selectedRowRecords.value.some((item: any) => {
      return item.processStatus !== 'DRAFT';
    });
    if (!disabled) {
      disabled = !deletePermission.value;
    }
    return disabled;
  });

  const selectAllChangeEvent: VxeTableEvents.CheckboxAll<listItem> = () => {
    const $table = tableRef.value;
    if ($table) {
      const records = $table.getCheckboxRecords();
      selectedRowKeys.value = records.map((item) => item.id);
      selectedRowRecords.value = records;
    }
  };

  const selectChangeEvent: VxeTableEvents.CheckboxChange<listItem> = () => {
    const $table = tableRef.value;
    if ($table) {
      const records = $table.getCheckboxRecords();
      selectedRowKeys.value = records.map((item) => item.id);
      selectedRowRecords.value = records;
    }
  };

  const hasSelected = computed(() => selectedRowKeys.value.length > 0);

  // 快捷设置列表选中值
  const setSelectedRowKeys = (keys: Key[]) => {
    const $table = tableRef.value;
    if ($table) {
      selectedRowKeys.value = keys;
      $table.setAllCheckboxRow(false);
    }
  };
  /**列表选中相关内容 */

  /**监听高度变化并重置表单高度 */
  const tableContainerRef = ref();
  const formContainerRef = ref();
  const isShowSearchForm = ref(true);
  const calcTableContainerHeight = () => {
    const formDom = formContainerRef.value;
    const formItemDom = formDom.querySelector('.ant-form-item');
    let formHeight = 0;
    if (formItemDom) {
      formHeight = formDom.offsetHeight;
    } else {
      isShowSearchForm.value = false;
    }
    if (formHeight) {
      tableContainerRef.value.style.height = `calc(100% - ${formHeight + 8}px)`;
    }
  };

  const redoHeight = () => {
    nextTick(() => {
      calcTableContainerHeight();
    });
  };

  const observer = new ResizeObserver((entries) => {
    const height = entries[0].target.offsetHeight;
    if (height) {
      redoHeight();
    }
  });

  useWindowSizeFn(calcTableContainerHeight, 280);
  onMountedOrActivated(() => {
    calcTableContainerHeight();
    if (formContainerRef.value) {
      observer.observe(formContainerRef.value);
    }
  });
  /**监听高度变化并重置表单高度 */
</script>

<style scoped lang="less">
  .pure-container {
    height: 100%;
    width: 100%;
    .form-container {
      width: 100%;
      min-height: 56px;
      background-color: #fff;
      border-radius: 8px;
      margin-bottom: 8px;
      padding: 12px 12px 4px 12px;
      box-sizing: border-box;

      :deep(.ant-form) {
        min-height: 32px;
      }
      :deep(.ant-form-item) {
        margin-bottom: 8px !important;
      }
    }
    .table-container {
      width: 100%;
      height: calc(100% - 64px);
      background-color: #fff;
      border-radius: 8px;
      .loading-container {
        width: 100%;
        height: calc(100% - 100px);
        position: absolute;
        background: rgba(255, 255, 255, 0.6);
        z-index: 1;
        & > .ant-spin {
          top: 22%;
          position: absolute;
          right: 50%;
          z-index: 2;
          transform: translateX(-50%);
        }
      }

      .operation-box {
        width: 100%;
        padding: 12px;
        box-sizing: border-box;
        .cyj-basic-table-header__tableTitle > * {
          margin-right: 12px;
        }
        .info-box {
          margin-top: 8px;
          .alert {
            height: 38px;
          }
        }
      }
      .table-page-container {
        width: 100%;
        height: calc(100% - 102px);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;
        .vex-table-container {
          width: 100%;
          height: calc(100% - 52px);
          padding: 0 12px;
          box-sizing: border-box;
        }
      }
    }
  }
  .colorText {
    display: inline-block;
    height: 20px;
    line-height: 20px;
    padding: 0 6px;
    border-radius: 8px;
    background-color: var(--bl-danger-c);
    color: #fff;
    font-size: 12px;
  }
  :deep(.ant-divider-vertical) {
    margin: 0 2px;
  }

  :deep(.ant-pagination) {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin: 0 !important;
    padding: 14px 20px;
    box-sizing: border-box;
    box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
    z-index: 1;
  }

  .approval-form-modal {
    /** 时间和数字输入框样式 */
    :deep(.ant-input-number) {
      width: 100%;
    }

    :deep(.ant-calendar-picker) {
      width: 100%;
    }
  }

  :where(.css-dev-only-do-not-override-xrhips).ant-btn > .anticon + span,
  :where(.css-dev-only-do-not-override-xrhips).ant-btn > span + .anticon {
    margin: 0;
  }
</style>
